#include "pthread.h"
#include "stdio.h"

// 初始化互斥锁
static pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;

void *thread_add_func(void *args)
{
    int *p = args;

    // 三个指令:取数据,累加,赋值
    // 加锁
    pthread_mutex_lock(&counter_mutex);
    *p = *p + 1;
    // 解锁
    pthread_mutex_unlock(&counter_mutex);
    return NULL;
}

int main(int argc, char const *argv[])
{
    int thread_num = 20000;
    pthread_t pts[thread_num];

    int num = 0;

    // 创建线程对参数进行累加处理
    for (int i = 0; i < thread_num; i++)
    {
        pthread_create(&pts[i], NULL, thread_add_func, &num);
    }

    // 等待所有线程执行结束
    for (int i = 0; i < thread_num; i++)
    {
        pthread_join(pts[i], NULL);
    }

    // 销毁锁
    pthread_mutex_destroy(&counter_mutex);

    // 打印累加后的值
    printf("累加后的数据num = %d \n", num);

    return 0;
}
